package yingke.com.yingke.ui.right.dao;

import android.os.Handler;
import android.os.Message;

import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import yingke.com.yingke.ui.right.bean.UserNodesBean;
import yingke.com.yingke.ui.right.utils.OkHttpClientUtils;

/**
 * Created by Administrator on 2016/10/20.
 */

public class DownAndAnalysis {


    private static JSONArray live_nodes;
    private static JSONArray user_nodes;

    public static void getData(final String path) {
        try {
            //通过okhttp下载json数据
            String json = OkHttpClientUtils.getStringFromUrl(path);
            //解析json数据
            JSONObject jsonObject = new JSONObject(json);
            live_nodes = jsonObject.getJSONArray("live_nodes");
            user_nodes = jsonObject.getJSONArray("user_nodes");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public static void getHeadData(final String path, final Handler handler) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                getData(path);
                Message message = Message.obtain();
                message.what = 0;
                message.obj = live_nodes;
                handler.sendMessage(message);
            }
        }).start();
    }

    public static void getListData(final String path, final Handler handler) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    getData(path);
                    JSONObject jsonObject = user_nodes.getJSONObject(0);
                    Gson gson = new Gson();
                    UserNodesBean userNodesBean = gson.fromJson(String.valueOf(jsonObject), UserNodesBean.class);
                    List<UserNodesBean.UsersBean> users = userNodesBean.getUsers();
                    Message message = Message.obtain();
                    message.what = 3;
                    message.obj = users;
                    handler.sendMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
